package io.gitee.hechenl.fastiotreport.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class RegexUtil {

    /**匹配所有整数（包括负数）*/
    private static final Pattern d_pattern = Pattern.compile("-?\\d+");

    /**匹配出括号项*/
    private static final Pattern bracket_pattern = Pattern.compile("\\(([^)]+)\\)");

    /**匹配括号项里的内容*/
    private static final String bracket_content_pattern = "\\((.+?)\\)";

    public static List<String> extractNumber(String str) {
        List<String> integers = new ArrayList<>();
        Matcher matcher = d_pattern.matcher(str);
        while (matcher.find()) {
            integers.add(matcher.group());
        }
        return integers;
    }

    /**
     * 替换数字
     */
    public static String replaceNumber(String str, Map<String, String> keyValueMap, String unknownTip) {
        Matcher matcher = d_pattern.matcher(str);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String comment = keyValueMap.getOrDefault(String.valueOf(matcher.group()), unknownTip);
            matcher.appendReplacement(result, comment);
        }
        matcher.appendTail(result);
        return result.toString();
    }

    /**
     * 替换首个括号内的内容
     */
    public static String replaceFirstInBracket(String str, String replacement) {
        return str.replaceFirst(bracket_content_pattern, replacement);
    }

    /**
     * 提取出括号项
     */
    public static List<String> extractBracketItems(String str) {
        List<String> itemList = new ArrayList<>();
        Matcher groupMatcher = bracket_pattern.matcher(str);
        while (groupMatcher.find()) {
            itemList.add(groupMatcher.group());
        }
        return itemList;
    }

    /**
     * 提取括号项里的数字
     */
    public static List<String> extractBracketNumber(String bracketItem) {
        String replaceStr = bracketItem.replace("(", "").replace(")", "");
        return Arrays.stream(replaceStr.split("\\+")).map(String::trim).collect(Collectors.toList());
    }


}
